//
//   BCSFoundationUtils.swift
//   BCFoundation
//
//   Created by Basic on 2019/6/12.
//

import UIKit.UIViewController
import UIKit.UIScrollView
import Foundation.NSThread

// MARK: - device info
/// 屏幕宽度
public let kBCSCREEN_WIDTH:CGFloat     = UIScreen.main.bounds.size.width/// 屏幕宽度
/// 正常屏幕高度，667，iphone 6、7、8
public let BCHEIGHT_NORMAL:CGFloat     = 667.0
/// 获取实时的屏幕宽度（旋转屏幕）
public func BCSCREEN_WIDTH() -> CGFloat {
    return UIScreen.main.bounds.size.width
}
/// 屏幕高度
public let kBCSCREEN_HEIGHT:CGFloat    = UIScreen.main.bounds.size.height
/// 获取实时的屏幕高度（旋转屏幕）
public func BCSCREEN_HEIGHT() -> CGFloat {
    return UIScreen.main.bounds.size.height
}
/// 屏幕高度
public let kBCSCREEN_SCALE:CGFloat     = UIScreen.main.scale
/// tab bar高度
public let kBCTABBAR_HEIGHT:CGFloat    = 49
/// iphone屏幕宽度比例
public let kBCSCREEN_PhoneWidthRatio:CGFloat   = (kBCSCREEN_WIDTH/375.0)
/// iphone屏幕高度比例
public let kBCSCREEN_PhoneHeightRatio:CGFloat  = (kBCSCREEN_HEIGHT/667.0)
/// ipad屏幕宽度比例
public let kBCSCREEN_PadWidthRatio:CGFloat     = (kBCSCREEN_WIDTH/1024.0)
/// ipad屏幕高度比例
public let kBCSCREEN_PadHeightRatio:CGFloat    = (kBCSCREEN_HEIGHT/768.0)

public func kBCAppKeyWindow() -> UIWindow? {
    return UIApplication.shared.delegate?.window ?? nil
}
public func kBCSystemVersion() -> Float? {
    return Float(UIDevice.current.systemVersion);
}
/// iphone4的宽度
public let kBCIsIPhone4Width:Bool = (kBCSCREEN_WIDTH==320.0)
/// iphone 6plus的宽度
public let kBCIsIPhone6PWidth:Bool = (kBCSCREEN_WIDTH==414)

/// 基于375宽度的适配
public func kBCAdaptHeight(_ x:CGFloat) ->CGFloat {
    var height:CGFloat = 0.0
    if BCSIsIPad {
        if UIApplication.shared.statusBarOrientation.isPortrait {
            height = 1024.0
        } else {
            
            height = 768.0
        }
    } else {
        if UIApplication.shared.statusBarOrientation.isPortrait {
            height = 667.0
        } else {
            
            height = 375.0
        }
    }
    return x/height*kBCSCREEN_HEIGHT
}
public func kBCAdaptWidth(_ x:CGFloat) ->CGFloat {
    var width:CGFloat = 0.0
    if BCSIsIPad {
        if UIApplication.shared.statusBarOrientation.isPortrait {
            width = 768.0
        } else {
            width = 1024.0
        }
    } else {
        if UIApplication.shared.statusBarOrientation.isPortrait {
            width = 375.0
        } else {
            width = 667.0
        }
    }
    return x/width*kBCSCREEN_WIDTH
}

// MARK: - iPad
/// 是否是 iPad
public let BCSIsIPad = (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad)

// MARK: - iphone x
/// 是否是 iphone x,判断是否有刘海
public func kBCIsIPhoneX() -> Bool {
    if #available(iOS 11, *) {
        guard let window = UIApplication.shared.delegate?.window, let window_ = window else {
            return false
        }
              
        if window_.safeAreaInsets.bottom > 0 {
            return true
        }
    }
    return false
}
/// nav bar 高度
public func kBCNAVBAR_HEIGHT() -> CGFloat {
    if kBCIsIPhoneX() && !UIApplication.shared.statusBarOrientation.isLandscape {
        //刘海屏幕，非横屏
        return kBCSTATUSBAR_HEIGHT()+44
    }
    else if BCSIsIPad {
        //iPad 高度70
        return 70
    }
    else {
        return 64
    }
}
/// 顶部安全距离
public let kBCScreenSafeAreaTop = kBCIsIPhoneX() ? 24 :  0
/// 底部安全距离
public let kBCScreenSafeAreaBottom = kBCIsIPhoneX() ? 34 :  0
/// 底部距离区分刘海屏
public let kBCScreenSafeFitBottom = kBCIsIPhoneX() ? 34 :  15

/// /// 状态栏高度，系统的高度
public func kBCSTATUSBAR_HEIGHT() -> CGFloat {
    return (UIApplication.shared.isStatusBarHidden ? ((kBCIsIPhoneX() ? 44 : 20)) : UIApplication.shared.statusBarFrame.size.height) 
}
/// 状态栏实际占用高度
public func kBCSTATUSBAR_FixedHeight() -> CGFloat {
    return (kBCIsIPhoneX() ? 35 : 0)/// iphone x 这里不用44，因为实际现实上没有占44
}

public func kBCAdjustsScrollViewInsetNever( _ controller:UIViewController?, _ view:UIScrollView) {
    if #available(iOS 11.0, *) {
        view.contentInsetAdjustmentBehavior = .never
    } else {
        controller?.automaticallyAdjustsScrollViewInsets = false;
    }
}
/** 适配iphone x,调整 tableFooterView */
public func BCAdjustTableFooterView(_ tableView: UITableView?) {
    let kSafeAreaBottom:CGFloat = CGFloat(kBCScreenSafeAreaBottom)
    if(kSafeAreaBottom>0) {
        tableView?.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView?.frame.size.width ?? 0, height: kSafeAreaBottom))
    }
}
/** 适配iphone x,调整 tableFooterView */
public func BCAdjustTableFooterViewWithOffset(_ tableView: UITableView?, _ offset:CGFloat) {
    let kSafeAreaBottom:CGFloat = CGFloat(kBCScreenSafeAreaBottom)
    if(kSafeAreaBottom>0 || offset>0) {
        tableView?.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView?.frame.size.width ?? 0, height: (kSafeAreaBottom+offset)))
    }
}


/// MARK: - thread safe
public func dispatch_main_async_bcsafe(_ block:@escaping () -> Void) {
    if (Thread.isMainThread) {
        block();
    } else {
        DispatchQueue.main.async(execute: block)
    }
}


/// MARK: - log
public func BCLog(_ msg: String?) {
    #if DEBUG
    NSLog(msg ?? "");
    #endif
}
public func BCLogDeinit(_ obj:AnyObject) {
    #if DEBUG
    NSLog("\(type(of: obj)) deinit");
    #endif
}


/// MARK: - MutlLanguage
public func BCLOC(_ key: String) -> String {
    return NSLocalizedString(key, comment: "")
}
public func BCLOC(_ key: String, _ bundleCls:AnyObject?) -> String {
    return NSLocalizedString(key, comment: "")
}


/// MARK: - String
/// #define     BCStrEmpty(a,b)     (a.length>0 && ![a isKindOfClass:[NSNull class]])?a:b
/// #define     kBCURLExpression    @"(?:(?:http|https):/// )?[a-zA-Z0-9./?:@\\-_=#]+\\.([a-zA-Z0-9./?:@\\-_=#])*"/// URL正则表达式
/// #define     kBCURLIntegralExpression    @"[a-zA-z]+:/// [^\\s]*"/// 完整的URL正则表达式
public let kBCURLStr = { (_ key: String) -> NSURL? in
    NSURL(string: key)
}

/// MARK: - 图片
public func kBCImgWidthURL<T>(_ imgurl: String?, _ width: T?) -> String? {
    if let kWidth = width {
        if (imgurl?.contains("?"))! {
            return imgurl?.appending("&imageView2/2/w/\(kWidth)")
        } else {
            return imgurl?.appending("?imageView2/2/w/\(kWidth)")
        }
    } else {
        return imgurl;
    }
}

